<template>
  <el-drawer v-model="dialogVisible" :destroy-on-close="true" size="100%" :title="dialogProps.title + '服务费'">
    <el-form
      ref="ruleFormRef"
      label-width="120px"
      label-suffix=" :"
      :rules="rules"
      :disabled="dialogProps.isView"
      :model="dialogProps.row"
      :hide-required-asterisk="dialogProps.isView"
    >
      <div class="mb20">
        <el-alert
          title="1.请主动告知顾客服务费收取规则, 以减少不必要的纠纷; 2.先就餐后付费的订单自动计算服务费, 同时在订单明细中展示服务费;"
          type="info"
          show-icon
        />
      </div>
      <el-form-item label="服务费名称" prop="name">
        <el-input class="width320" id="name" v-model="dialogProps.row!.name" placeholder="请输入服务费名称" clearable />
      </el-form-item>
      <el-form-item label="服务费方案" prop="feeType">
        <el-radio-group v-model="dialogProps.row!.feeType" id="feeType" @change="changeFeeType">
          <el-radio :value="1">按就餐人数</el-radio>
          <el-radio :value="2">按每桌台收取</el-radio>
          <el-radio :value="3">菜品惠后价×设置比例</el-radio>
          <el-radio :value="4">菜品价格合计×设置比例</el-radio>
          <el-radio :value="5">按时间收取</el-radio>
          <el-radio :value="6">消费补齐</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label=""
        prop="feeValue"
        v-if="dialogProps.row!.feeType===1 || dialogProps.row!.feeType===2 ||dialogProps.row!.feeType===6"
      >
        <div>
          <div class="mb14" v-if="dialogProps.row!.feeType===6">
            <el-text type="info">当桌台消费金额小于补齐金额时，桌台将按照补齐金额收取费用</el-text>
          </div>
          <div>
            <el-text v-if="dialogProps.row!.feeType===6" class="mr10">消费补齐金额</el-text>
            <el-input class="width320" id="feeValue" v-model.number="dialogProps.row!.feeValue" placeholder="请输入金额">
              <template #append>
                <el-text v-if="dialogProps.row!.feeType===1">元/位</el-text>
                <el-text v-if="dialogProps.row!.feeType===2">元/桌</el-text>
                <el-text v-if="dialogProps.row!.feeType===6">元</el-text>
              </template>
            </el-input>
          </div>
        </div>
      </el-form-item>
      <el-form-item prop="feeValue" v-if="dialogProps.row!.feeType===3 || dialogProps.row!.feeType===4">
        <el-input class="width320" id="feeValue" v-model.number="dialogProps.row!.feeValue" placeholder="请输入数字">
          <template #append> % </template>
        </el-input>
      </el-form-item>
      <el-form-item v-if="dialogProps.row!.feeType===5">
        <div>
          <el-text class="mb10" type="info">扫码点餐仅支持「点餐」模式，和「点餐+支付」-「后付」模式的点餐功能</el-text>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item prop="unitValue" label-width="0">
                <el-input v-model.number="dialogProps.row!.unitValue" id="unitValue">
                  <template #prepend>每</template>
                  <template #append>
                    <el-select class="width100" v-model="dialogProps.row!.unit">
                      <el-option label="小时" :value="1" />
                      <el-option label="分钟" :value="2" />
                    </el-select>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="feeValue" label-width="0">
                <el-input v-model.number="dialogProps.row!.feeValue" id="feeValue" placeholder="请输入金额">
                  <template #append>元</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form-item>
      <el-form-item v-if="dialogProps.row!.feeType===3 || dialogProps.row!.feeType===4 || dialogProps.row!.feeType===6">
        <div>
          <div>
            <el-text>不计入服务费菜品:</el-text>
            <el-text class="ml10 pointer" type="primary" @click="openSelectTreeTable('选择菜品', 0)"> 选择菜品 </el-text>
            <el-text
              class="ml10 pointer"
              type="primary"
              @click="openSelectTreeTable('选择菜品', 0)"
              v-if="dialogProps.row!.foodSpecList.length > 0"
            >
              ( 已选择 {{ dialogProps.row!.foodSpecList.length }} 个 )
            </el-text>
          </div>
          <div class="flex gap-2">
            <el-tag
              class="mr10"
              v-for="(tag, tx) in dialogProps.row!.foodSpecList"
              :key="tag.id"
              closable
              :type="tag.type"
              @close="closeRow(tx, 'foodSpecList')"
            >
              {{ tag.name }}
            </el-tag>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="POS端手动修改服务费金额" prop="posChange" label-width="200px">
        <el-radio-group v-model="dialogProps.row!.posChange">
          <el-radio :value="1">允许</el-radio>
          <el-radio :value="0">不允许</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="服务费状态" prop="status">
        <el-radio-group v-model="dialogProps.row!.status">
          <el-radio :value="1">开启</el-radio>
          <el-radio :value="0">关闭</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="适用桌台" prop="deskList">
        <div>
          <div>
            <el-text class="ml10 pointer" type="primary" @click="openSelectTreeTable('选择桌台', 1)"> 选择桌台 </el-text>
            <el-text
              class="ml10 pointer"
              type="primary"
              @click="openSelectTreeTable('选择桌台', 1)"
              v-if="dialogProps.row!.deskList.length > 0"
            >
              ( 已选择 {{ dialogProps.row!.deskList.length }} 个 )
            </el-text>
          </div>
          <div class="flex gap-2">
            <el-tag
              class="mr10"
              v-for="(tag, tx) in dialogProps.row!.deskList"
              :key="tag.id"
              closable
              :type="tag.type"
              @close="closeRow(tx, 'deskList')"
            >
              {{ tag.name }}
            </el-tag>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="生效日期" prop="validityType">
        <el-radio-group v-model="dialogProps.row!.validityType">
          <el-radio :value="0">永久有效</el-radio>
          <el-radio :value="1">自定义有效期</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="自定义日期" prop="validityRange" v-if="dialogProps.row!.validityType===1">
        <div>
          <el-date-picker
            class="width280"
            v-model="dialogProps.row!.validityRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </div>
      </el-form-item>
      <el-form-item label="生效星期" prop="validityDay">
        <el-checkbox class="mr30" v-model="checkWeekAll" :indeterminate="isIndeterminate" @change="checkWeekAllChange">
          全部
        </el-checkbox>
        <el-checkbox-group v-model="dialogProps.row!.validityDay" @change="checkedWeeksChange">
          <el-checkbox v-for="week in weeks" :key="week.value" :label="week.label" :value="week.value">{{
            week.label
          }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="生效时间" prop="validityTime">
        <div>
          <div class="mb10" v-for="(tim, tix) in dialogProps.row!.validityTime" :key="tix">
            <el-time-picker
              v-model="dialogProps.row!.validityTime[tix]"
              class="width200"
              is-range
              range-separator="至"
              start-placeholder="请选择时间"
              end-placeholder="请选择时间"
              format="HH:mm"
              value-format="HH:mm"
            >
            </el-time-picker>
            <el-button
              class="ml20"
              type="danger"
              size="small"
              :icon="Delete"
              circle
              v-if="tix > 0"
              @click="closeRow(tix, 'validityTime')"
            />
          </div>
          <el-text class="pointer" type="primary" @click="addTimes">添加一个时间段</el-text>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false"> 取消 </el-button>
      <el-button v-show="!dialogProps.isView" type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-drawer>
  <SelectTreeTable @selected-list="handleSelectedTreeList" ref="selectTreeTableRef" />
</template>

<script setup lang="ts" name="RuleDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import SelectTreeTable from "@/components/SelectTreeData/index.vue";
import { Delete } from "@element-plus/icons-vue";
import { getFoodCategoryList, getGoodsSingleItem } from "@/api/modules/goods";
import { getFoodDeskCategoryList, getFoodDeskList, getEditFoodDeskFee } from "@/api/modules/restaurant";
import { weeks } from "@/utils/serviceDict";
import { Restaurant } from "@/api/interface";

const rules = reactive({
  name: [{ required: true, message: "此项必填" }],
  feeValue: [
    { required: true, message: "此项必填" },
    { type: "number", min: 0.01, max: 999999.99, message: "请输入介于0.01到999999.99之间的数字" }
  ],
  unitValue: [
    { required: true, message: "此项必填" },
    { type: "number", message: "只能输入数字" },
    { type: "number", min: 1, message: "不能小于1" }
  ],
  deskList: [{ required: true, message: "请至少选择一个桌台" }],
  validityRange: [{ required: true, message: "请选择日期" }],
  validityDay: [{ required: true, message: "请选择星期" }]
});

interface DialogProps {
  title: string;
  isView: boolean;
  row: Partial<Restaurant.ResFoodDeskFeeList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}
const checkWeekAll = ref(true);
const isIndeterminate = ref(false);
const dialogVisible = ref(false);

const dialogProps = ref<DialogProps>({
  isView: false,
  title: "",
  row: {}
});

// 接收父组件传过来的参数
const acceptParams = async (params: dialogProps) => {
  dialogProps.value = params;
  if (dialogProps.value.title !== "新增") {
    getEditFoodDeskFee({ id: dialogProps.value.row.id }).then(res => {
      dialogProps.value.row = res.data;
    });
  }
  dialogVisible.value = true;
};

const checkWeekAllChange = (val: boolean) => {
  dialogProps.value.row.validityDay = val ? weeks.map(im => im.value) : [];
  isIndeterminate.value = false;
};
const checkedWeeksChange = (value: string[]) => {
  const checkedCount = value.length;
  checkWeekAll.value = checkedCount === weeks.map(im => im.value).length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < weeks.map(im => im.value).length;
};

const changeFeeType = (val: number) => {
  dialogProps.value.row.feeValue = null;
  dialogProps.value.row.unitValue = null;
  if (val !== 3 && val !== 4 && val !== 6) {
    dialogProps.value.row.foodSpecList = [];
  }
};

const selectTreeTableRef = ref<InstanceType<typeof SelectTreeTable> | null>(null);
const openSelectTreeTable = (title: string, index: number) => {
  const params = {
    title,
    isView: false,
    index: index,
    mate: index === 0 ? "foodSpecId" : "id",
    selTags: index === 0 ? dialogProps.value.row.foodSpecList : dialogProps.value.row.deskList,
    columns:
      index === 0
        ? [
            { type: "selection", width: 60 },
            { prop: "name", label: "菜品名称", align: "left", minWidth: 160 },
            { prop: "foodTypeName", label: "分类", minWidth: 100 },
            { prop: "foodSpecName", label: "规格", minWidth: 100 },
            { prop: "posPrice", label: "菜品价格", minWidth: 100 }
          ]
        : [
            { type: "selection", width: 60 },
            { prop: "name", label: "桌台名称", align: "left", minWidth: 160 },
            { prop: "manQty", label: "标准用餐人数", minWidth: 120 },
            { prop: "number", label: "数字助记码", minWidth: 100 }
          ],
    idName: index === 0 ? "foodCategoryId" : "typeId",
    treeApi: index === 0 ? getFoodCategoryList : getFoodDeskCategoryList,
    api: index === 0 ? getGoodsSingleItem : getFoodDeskList
  };
  selectTreeTableRef.value?.acceptParams(params);
};

const handleSelectedTreeList = (val: any) => {
  if (val.index === 0) {
    dialogProps.value.row.foodSpecList = val.list.map(im => {
      return {
        name: im.name + "-" + im.foodSpecName,
        id: im.foodSpecId
      };
    });
  } else if (val.index === 1) {
    dialogProps.value.row.deskList = val.list.map(im => {
      return {
        name: im.name,
        id: im.id
      };
    });
  }
};

const closeRow = (ix: number, type: string) => {
  dialogProps.value.row[type].splice(ix, 1);
};

const addTimes = () => {
  dialogProps.value.row.validityTime.push([]);
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    console.log(dialogProps.value.row);
    if (!valid) return;
    try {
      await dialogProps.value.api!(dialogProps.value.row);
      ElMessage.success({ message: `${dialogProps.value.title}服务费成功！` });
      dialogProps.value.getTableList!();
      dialogVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
